package com.xiaoc.bulldozer.facade.impl;

import com.xc.framework.cache.manager.CacheManager;
import com.xc.framework.common.base.ResponseCode;
import com.xc.framework.common.exception.BusinessException;
import com.xiaoc.bulldozer.common.dto.LoginUserDto;
import com.xiaoc.bulldozer.common.dto.UserDto;
import com.xiaoc.bulldozer.common.dto.UserRolesQueryDto;
import com.xiaoc.bulldozer.common.model.Role;
import com.xiaoc.bulldozer.common.model.User;
import com.xiaoc.bulldozer.common.model.UserRole;
import com.xiaoc.bulldozer.common.service.UserRoleService;
import com.xiaoc.bulldozer.common.service.UserService;
import com.xiaoc.bulldozer.facade.UserFacade;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * user 实现类
 *
 * @author parcel
 */
@Service("userFacade")
public class UserFacadeImpl implements UserFacade {

    private static final long SESSION_TIMEOUT = 60 * 60000L;

    @Resource(name = "remoteCacheManager")
    private CacheManager remoteCacheManager;

    @Resource(name = "userService")
    private UserService userService;

    @Resource(name = "userRoleService")
    private UserRoleService userRoleService;

    private String generateSessionId() {
        return UUID.randomUUID().toString();
    }

    @Override
    public LoginUserDto getCurrentLoginUser(String sessionId) {
        return StringUtils.isBlank(sessionId) ? null : (LoginUserDto) remoteCacheManager.get(sessionId);
    }

    @Override
    public void login(LoginUserDto loginUserDto) {
        String sessionId = generateSessionId();
        loginUserDto.setSessionId(sessionId);
        remoteCacheManager.put(sessionId, loginUserDto, SESSION_TIMEOUT);
    }

    @Override
    public void updateSession(String sessionId) {
        LoginUserDto loginUserDto = this.getCurrentLoginUser(sessionId);
        if (loginUserDto != null) {
            remoteCacheManager.replace(sessionId, loginUserDto, SESSION_TIMEOUT);
        }
    }

    @Override
    public void logout(String sessionId) {
        remoteCacheManager.remove(sessionId);
    }

    @Override
    public Integer queryUserCount(UserDto userDto) {
        return userService.queryUserCount(userDto);
    }

    @Override
    public List<UserDto> queryUserList(UserDto userDto) {
        return userService.queryUserList(userDto);
    }

    @Override
    public User registUser(UserDto userDto) {

        User user = new User();
        user.setLoginName(userDto.getLoginName());
        user.setLoginPwd(userDto.getLoginPwd());
        user.setName(userDto.getName());

        userService.createUser(user);

        List<UserRole> userRoleList = new ArrayList<UserRole>();
        UserRole userRole = new UserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(Role.BUSINESS_TAOKE);
        userRoleList.add(userRole);
        userRoleService.saveBatch(userRoleList);

        return user;
    }

    @Override
    public void createUser(UserDto userDto) {

        User user = new User();
        user.setLoginName(userDto.getLoginName());
        user.setLoginPwd(userDto.getLoginPwd());
        user.setName(userDto.getName());

        userService.createUser(user);

        if (userDto.getArrRoleId() != null && userDto.getArrRoleId().length > 0) {
            List<UserRole> userRoleList = new ArrayList<UserRole>();
            for (int i = 0; i < userDto.getArrRoleId().length; i++) {
                if (StringUtils.isNotBlank(userDto.getArrRoleId()[i])) {
                    UserRole userRole = new UserRole();
                    userRole.setUserId(user.getId());
                    userRole.setRoleId(Integer.parseInt(userDto.getArrRoleId()[i]));
                    userRoleList.add(userRole);
                }
            }
            userRoleService.saveBatch(userRoleList);
        }

    }

    @Override
    public void updateUser(UserDto userDto) {

        User user = userService.getUserById(userDto.getId());
        if (user == null) {
            throw new BusinessException(ResponseCode.INTERNAL_ERROR, "用户信息不存在");
        }
        user.setLoginName(userDto.getLoginName());
        user.setLoginPwd(userDto.getLoginPwd());
        user.setName(userDto.getName());

        userService.updateUser(user);

        userRoleService.deleteByUserId(userDto.getId());
        String[] arrRoleId = userDto.getArrRoleId();
        int roleLen = arrRoleId.length;

        if (arrRoleId != null && roleLen > 0) {
            List<UserRole> userRoleList = new ArrayList<UserRole>();
            for (int i = 0; i < roleLen; i++) {
                if (StringUtils.isNotBlank(arrRoleId[i])) {
                    UserRole userRole = new UserRole();
                    userRole.setUserId(user.getId());
                    userRole.setRoleId(Integer.parseInt(arrRoleId[i]));
                    userRoleList.add(userRole);
                }
            }
            userRoleService.saveBatch(userRoleList);
        }

    }

    @Override
    public void delUser(Integer userId) {
        userRoleService.deleteByUserId(userId);
        userService.deleteUser(userId);
    }

    @Override
    public void lockUser(Integer userId, Integer lockState) {
        User user = userService.getUserById(userId);
        user.setEnableStatus(lockState);

        userService.updateLockState(user);
    }

    @Override
    public void updatePassword(Integer userId, String password) {
        User user = new User();
        user.setId(userId);
        user.setLoginPwd(password);
        userService.updatePassword(user);
    }

    @Override
    public User getUserById(Integer userId) {
        return userService.getUserById(userId);
    }

    @Override
    public Map<Integer, UserRolesQueryDto> getUserRoleMap() {

        List<UserRolesQueryDto> userRolesQueryDtoList = userRoleService.getAllUserRoleList();
        Map<Integer, UserRolesQueryDto> userRolesQueryDtoMap = new HashMap<Integer, UserRolesQueryDto>();
        if (CollectionUtils.isEmpty(userRolesQueryDtoList)) {
            return userRolesQueryDtoMap;
        }

        for (UserRolesQueryDto userRolesQueryDto : userRolesQueryDtoList) {
            if (userRolesQueryDto.getUserId() != null) {
                userRolesQueryDtoMap.put(userRolesQueryDto.getUserId(), userRolesQueryDto);
            }
        }

        return userRolesQueryDtoMap;
    }

}
